package com.yx.controller;

import com.yx.entity.Book;
import com.yx.entity.Cart;
import com.yx.entity.CartItem;
import com.yx.service.IBookService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Collection;
import java.util.Map;

@RestController
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private IBookService bs;
    @GetMapping("/putCart/{bid}/{count}")
    public Cart putCart(@PathVariable("bid") int bid,@PathVariable Integer count, HttpSession session){
        Cart cart=(Cart)session.getAttribute("cart");
        if(cart==null){
            //没有cart对象
            cart=new Cart();
            Map<Integer, CartItem> buyMap = cart.getBuyMap();
            //从数据库里面查出book对象
            Book book = bs.getById(bid);
            CartItem ci=new CartItem(book,count);
            buyMap.put(bid,ci);
        }else{
            Map<Integer, CartItem> buyMap = cart.getBuyMap();
//            if(buyMap.containsKey(bid)){
//                //图书在cart购物车里面
//                CartItem ci = buyMap.get(bid);
//                ci.setCount(ci.getCount()+1);
//            }else{
//                //从数据库里面查出book对象
//                Book book = bs.getById(bid);
//                CartItem ci=new CartItem(book,1);
//                buyMap.put(bid,ci);
//            }
                Book book = bs.getById(bid);
                CartItem ci=new CartItem(book,count);
                buyMap.put(bid,ci);
        }
        calMoney(cart);

        session.setAttribute("cart",cart);
        return cart;
    }
    @GetMapping("/myCart")
    public Cart selectMyCart(HttpSession session){
        Cart cart = (Cart)session.getAttribute("cart");
        return cart;
    }
    @DeleteMapping("/delete/{id}")
    public Cart delete(@PathVariable("id")int id,HttpSession session){
        Cart cart=(Cart)session.getAttribute("cart");
        cart.getBuyMap().remove(id);
        calMoney(cart);

        session.setAttribute("cart",cart);
        return cart;
    }
    //计算购物车里面的节省金额和总金额
    private void calMoney(Cart cart) {
        //计算总金额
        Map<Integer, CartItem> buyMap = cart.getBuyMap();
        //遍历map集合
        Collection<CartItem> values = buyMap.values();
        double saveMoney = 0;
        double totalMoney = 0;
        for(CartItem ci:values){
            int count = ci.getCount();
            double dangPrice = ci.getBook().getDangprice();
            double borrowPrice=ci.getBook().getBorrowPrice();
            Double price = ci.getBook().getBookPrice();
            totalMoney+=dangPrice;
            totalMoney+=borrowPrice*count;
            saveMoney+=(price-dangPrice)*count;
        }
        cart.setSaveMony(saveMoney);
        cart.setTotalMoney(totalMoney);
    }
}
